package com.chen.service.impl;

import com.chen.handler.MyException;
import com.chen.mapper.StudentMapper;
import com.chen.entity.Student;
import com.chen.entity.vo.ResultCodeEnum;
import com.chen.service.StudentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
@Transactional
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;


    /**
     * 查询所有学生
     * @return
     */
    @Transactional(readOnly = true)
    @Override
    public List<Student> selectAll() {
        return studentMapper.selectAll();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public Student selectById(Integer id) {
        Student student=studentMapper.selectById(id);
        return student;
    }

    /**
     * 根据学号查询
     * @param sid
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public Student selectBySId(String sid) {
        Student student= studentMapper.selectBySId(sid);
        return student;
    }

    /**
     * 新增学生
     * @param student
     */
    @Override
    public void addStudent(Student student) {
        if(studentMapper.selectBySId(student.getSid())!=null){
            System.out.println("学号重复");
            throw  new MyException(ResultCodeEnum.Data_Error);
        }
        studentMapper.addStudent(student);

    }

    /**
     * 根据id删除
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
       Integer row= studentMapper.deleteById(id);
    }


    /**
     * 根据id修改
     * @param student
     */
    @Override
    public void editById(Student student) {
        if(studentMapper.selectBySId(student.getSid())!=null){
            System.out.println("学号重复");
            throw  new MyException(ResultCodeEnum.Data_Error);
        }
        studentMapper.updateById(student);
    }

    /**
     * 条件查询
     *
     * @param studentDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Transactional(readOnly = true)
    @Override
    public PageInfo<Student> selectByCondition(Student studentDto, Integer pageNum, Integer pageSize) {
        //开启分页
        PageHelper.startPage(pageNum,pageSize);
        List<Student> studentList=studentMapper.selectByCondition(studentDto);
        return new PageInfo<>(studentList);
    }
}
